package com.letv.business.flow.PlayFlowState;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import com.ledim.app.LeDimApplication;
import com.ledim.utils.LogUtil;
import com.letv.ads.AdsManager;
import com.letv.android.client.LetvSDK;
import com.letv.android.young.client.R;
//import com.letv.business.flow.PlayFlowModule.Application;
import com.letv.business.flow.PlayFlowEvents.PlayUrlPrepareEvent;
import com.letv.business.flow.PlayFlowEvents.StartPlayEvent;
import com.letv.business.flow.album.AlbumPlayFlow;
import com.letv.business.flow.album.AlbumPlayFlowObservable;
import com.letv.business.flow.album.listener.LoadLayoutFragmentListener;
import com.letv.business.flow.album.listener.PlayVideoFragmentListener;
import com.letv.business.flow.album.model.AlbumPlayInfo;
import com.letv.business.flow.album.model.AlbumUrl;
import com.letv.business.flow.play.PlayStatisticsUtils;
import com.letv.component.player.core.LetvMediaPlayerManager;
import com.letv.core.api.LetvRequest;
import com.letv.core.bean.AlbumPayInfoBean;
import com.letv.core.bean.DDUrlsResultBean;
import com.letv.core.bean.DataHull;
import com.letv.core.bean.RealPlayUrlInfoBean;
import com.letv.core.bean.VideoBean;
import com.letv.core.constant.NetworkConstant;
import com.letv.core.constant.PlayConstant;
import com.letv.core.db.PreferencesManager;
import com.letv.core.network.volley.Volley;
import com.letv.core.network.volley.VolleyRequest;
import com.letv.core.network.volley.VolleyResponse;
import com.letv.core.network.volley.toolbox.SimpleResponse;
import com.letv.core.network.volley.toolbox.VolleyDbCache;
import com.letv.core.network.volley.toolbox.VolleyNoCache;
import com.letv.core.parser.RealPlayUrlInfoParser;
import com.letv.core.utils.BaseTypeUtils;
import com.letv.core.utils.LetvLogApiTool;
import com.letv.core.utils.LetvSDKUtils;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.NetworkUtils;
import com.letv.core.utils.PlayUtils;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.UIsUtils;
import com.letv.datastatistics.util.DataConstant;
import com.letv.datastatistics.util.PageIdConstant;
import com.letv.pp.func.CdeHelper;
import com.letv.pp.url.PlayUrl;

import org.greenrobot.eventbus.Subscribe;

/**
 * Created by jipengfei on 2016/10/31.
 */
public class PlayUrlPrepareState extends BasePlayState{

    //从cde获取真实地址和从网络获取真实地址需要的时长，用于统计
    private long  getRealUrlFromNetConsumetime,cdeConsumetime;

    @Override
    protected void injectDependencies() {
        LeDimApplication.getComponentInstance().inject(this);
    }

    @Override
    public void onStateApplied(){
        super.onStateApplied();

        mPlayFlow = getProvider().providPlayFlow();

        LogInfo.log("sguotao", "进入PlayUrlPrepareState");
        requestRealPlayUrl();

    }

    @Override
    public void onStateLeft() {
        super.onStateLeft();

    }

    @Subscribe
    public void onStartPlayEvent(StartPlayEvent startPlayEvent) {

//        playUrlPrepareEvent.requestRealPlayUrl();
        fireEvent(PlayFlowEvents.Play_OnCall);
    }
    /**
     * 请求真实播放地址
     */
    protected void requestRealPlayUrl() {
        VideoBean mCurrentPlayingVideo = mPlayFlow.getPlayingVideo();

        PlayVideoFragmentListener mVideoListener = mPlayFlow.getVideoListener();

        if (mCurrentPlayingVideo == null) {
            return;
        }

        if (mVideoListener != null) {
            mVideoListener.setIsSeekTo0(true);
        }
        setP2pMode();

        if (!onPreRequestRealPlayUrl()) {
            return;
        }
//        else if (mFlowStyle == AlbumPlayFlow.FlowStyle.Topic) {
//            shouldShowNetChangeDialog();
//        }

        if (mPlayFlow.getDdUrlsResult() == null) {
            return;
        }
//        // add by ccx for Event upload
//        getRealUrlFromNetConsumetime = 0;
//        cdeConsumetime = 0;
        getRealUrlInfoByCde();
    }

    /**
     * 从cde获取真实播放地址
     *
     * @return
     */
    protected void getRealUrlInfoByCde() {
        final String REQUEST_REAL_URL_BY_CDE = "albumFlowTag_" + "requestRealurlByCde";
        Volley.getQueue().cancelWithTag(REQUEST_REAL_URL_BY_CDE);
        final Context mContext = mPlayFlow.getContext();
        final long cdeStartTime = System.currentTimeMillis();
        mPlayFlow.getPlayInfo().getRealUrlConsumeTime = System.currentTimeMillis();
        new LetvRequest<RealPlayUrlInfoBean>(mContext).setTag(REQUEST_REAL_URL_BY_CDE)
                .setRequestType(VolleyRequest.RequestManner.CACHE_ONLY)
                .setCache(new VolleyDbCache<RealPlayUrlInfoBean>() {

                    @Override
                    public RealPlayUrlInfoBean get(
                            VolleyRequest<?> request) {
                        //                PreferencesManager.getInstance(mContext).isLinkShellSwitch();

                        DDUrlsResultBean mDdUrlsResult = mPlayFlow.getDdUrlsResult();

                        if (mDdUrlsResult == null
                               /* || mIsWo3GUser*/) {
                            return null;
                        }

                        AlbumUrl mAlbumUrl = mPlayFlow.getAlbumUrl();
                         AlbumPayInfoBean mPayInfo =  mPlayFlow.getPayInfo();
                         AlbumPlayInfo mPlayInfo = mPlayFlow.getPlayInfo();

                        mAlbumUrl.ddUrl =
                                PlayUtils.getDdUrl(mContext, mDdUrlsResult
                                                .getDdurls(),
                                        mPayInfo == null ? ""
                                                : mPayInfo
                                                .getToken(), PreferencesManager
                                                .getInstance(mContext)
                                                .getUserId(),
                                        mPlayFlow.getVid() + "");
                        LogInfo.log("sguotao",
                                "状态机防盗链:" + mAlbumUrl.ddUrl);
                        mPlayFlow.addPlayInfo("开始从cde获取播放地址,调度地址", mAlbumUrl.ddUrl);
                        //                        BaseApplication.getInstance().reStartCde();
                        LetvSDKUtils.reStartCde(mContext);
                        // p2p播放
                        //                        CdeHelper cdeHelper = BaseApplication.getInstance().getCdeHelper();
                        CdeHelper cdeHelper =
                                LetvSDKUtils.getCdeHelper(mContext);
                        if (mPlayFlow.isP2pMode() && cdeHelper != null &&
                                !NetworkUtils.checkIsProxyNet(mContext)) {
                            mAlbumUrl.p2pUrl =
                                    mAlbumUrl.ddUrl;
                            // 加密开关开启,获取加密过后的url
                            if (PreferencesManager.getInstance(mContext)
                                    .isLinkShellSwitch()) {
                                mAlbumUrl.linkShellUrl =
                                        PlayUtils.getURLFromLinkShell(mContext, mAlbumUrl.p2pUrl);
                                mPlayFlow.addPlayInfo("从cde获取播放地址,linkShell", mAlbumUrl.linkShellUrl);
                                LogInfo.log("sguotao",
                                        "状态机linkShell:" +
                                                mAlbumUrl.linkShellUrl);
                            }
                            if (!TextUtils.isEmpty(mAlbumUrl.linkShellUrl)) {
                                mAlbumUrl.p2pUrl =
                                        mAlbumUrl.linkShellUrl;
                                mPlayInfo.mVideoSend =
                                        "vsend=P2P";
                                mPlayInfo.getRealUrlConsumeTime =
                                        System.currentTimeMillis() -
                                                mPlayInfo.getRealUrlConsumeTime;
                                // 执行p2p播放
                                mAlbumUrl.p2pPlayer =
                                        new PlayUrl(cdeHelper.getServicePort(), mAlbumUrl.p2pUrl, "", "");// "playpos=" +
                                // getPlayRecordStep()：等内核播放器支持firstSeek之后，再加

                                mAlbumUrl.realUrl =
                                        mAlbumUrl.p2pPlayer.getPlay();
                                if (TextUtils.isEmpty(mAlbumUrl.realUrl)) {
                                    return null;
                                }
                                mPlayFlow.addPlayInfo("从cde获取播放地址成功,真实地址", mAlbumUrl.realUrl);
                                RealPlayUrlInfoBean bean =
                                        new RealPlayUrlInfoBean();
                                bean.setRealUrl(mAlbumUrl.realUrl);
//                                mPlayFlow.setmAlbumUrl(mAlbumUrl);
                                return bean;
                            }
                        }
                        return null;
                    }

                    @Override
                    public void add(VolleyRequest<?> request,
                                    RealPlayUrlInfoBean response) {
                    }
                })
                .setCallback(new SimpleResponse<RealPlayUrlInfoBean>() {

                    @Override
                    public void onCacheResponse(
                            VolleyRequest<RealPlayUrlInfoBean> request,
                            RealPlayUrlInfoBean result,
                            DataHull hull,
                            VolleyResponse.CacheResponseState state) {
                        LogInfo.log("sguotao",
                                "****************从cde获取真实播放地址消耗时间" +
                                        (System.currentTimeMillis() -
                                                cdeConsumetime) +
                                        "毫秒****************");
                        cdeConsumetime =
                                System.currentTimeMillis() -
                                        cdeStartTime;
                        if (state ==
                                VolleyResponse.CacheResponseState.SUCCESS) {
                            LogInfo.log("sguotao", "从cde获取真实地址成功!");
                            onAfterFetchRealUrl(result, true);
                        } else {
                            LogInfo.log("sguotao", "从cde获取真实地址失败!");
                            getRealUrlFromNet();
                        }
                    }

                })
                .add();
    }

    /**
     * 从网络获取真实播放地址
     */
    protected void getRealUrlFromNet() {
        final String REQUEST_REAL_URL = ALBUM_FLOW_TAG + "requestRealurl";
        DDUrlsResultBean mDdUrlsResult = mPlayFlow.getDdUrlsResult();
        AlbumPayInfoBean mPayInfo =  mPlayFlow.getPayInfo();


        if (BaseTypeUtils.isArrayEmpty(mDdUrlsResult.getDdurls())) {
            return;
        }
        final long startTime = System.currentTimeMillis();
        final String url = PlayUtils.getRealUrl(mPlayFlow.getContext(), mDdUrlsResult.getDdurls(),
                mPayInfo == null ? ""
                        : mPayInfo.getToken(), PreferencesManager.getInstance(mPlayFlow.getContext())
                        .getUserId(), mPlayFlow.getVid() + "");
        if (TextUtils.isEmpty(url)) {
            return;
        }
        mPlayFlow.addPlayInfo("从cde获取播放地址失败,开始从网络获取播放地址", url);

        Volley.getQueue().cancelWithTag(REQUEST_REAL_URL);

        new LetvRequest<RealPlayUrlInfoBean>(mPlayFlow.getContext()).setUrl(url)
                .setParser(new RealPlayUrlInfoParser())
                .setCache(new VolleyNoCache())
                .setMaxRetries(2)
                .setRequestType(VolleyRequest.RequestManner.NETWORK_ONLY)
                .setTag(REQUEST_REAL_URL)
                .setCallback(new SimpleResponse<RealPlayUrlInfoBean>() {

                    @Override
                    public void onNetworkResponse(
                            VolleyRequest<RealPlayUrlInfoBean> request,
                            RealPlayUrlInfoBean result,
                            DataHull hull,
                            VolleyResponse.NetworkResponseState state) {
                        LogInfo.log("sguotao",
                                "requestRealPlayUrl:" +
                                        state);
                        AlbumPlayInfo mPlayInfo = mPlayFlow.getPlayInfo();

                        getRealUrlFromNetConsumetime =
                                System.currentTimeMillis() -
                                        startTime;
                        mPlayInfo.mRetryNum =
                                request.getRetryPolicy()
                                        .getRetries();
                        mPlayInfo.getRealUrlConsumeTime =
                                System.currentTimeMillis() -
                                        mPlayInfo.getRealUrlConsumeTime;

                        LoadLayoutFragmentListener mLoadListener = mPlayFlow.getLoadListener();
                        AlbumPlayFlowObservable mObservable = mPlayFlow.getObserver();
                        if (state ==
                                VolleyResponse.NetworkResponseState.SUCCESS) {
                            mPlayFlow.addPlayInfo("从网络获取播放地址成功", url);
                            result.setDdUrl(url);
                            onAfterFetchRealUrl(result, false);
                        } else if (state ==
                                VolleyResponse.NetworkResponseState.NETWORK_NOT_AVAILABLE) {
                            mLoadListener.requestError("", "");
                            mObservable.notifyObservers(new AlbumPlayFlowObservable.PlayErrorCodeNotify("", true));
                            //                        mTrailListener.hide();
//                            mPlayCallBackState = 6;
                        } else if (state ==
                                VolleyResponse.NetworkResponseState.NETWORK_ERROR) {
                            mLoadListener.requestError(mPlayFlow.getContext()
                                    .getString(R.string.commit_error_info), PlayConstant.PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED);
                            //                        mTrailListener.hide();
                            mObservable.notifyObservers(new AlbumPlayFlowObservable.PlayErrorCodeNotify(PlayConstant.PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED, true));
//                            mPlayCallBackState = 6;
                            // 统计
                            PlayStatisticsUtils.staticticsErrorInfo(mPlayFlow.getContext(),mPlayFlow, DataConstant.ERRORCODE.REQUEST_PLAY_NET_ER_ERROR, "playerError", 0, -1);
//                           mPlayFlow.staticticsErrorInfo(mPlayFlow.getContext(), DataConstant.ERRORCODE.REQUEST_PLAY_NET_ER_ERROR, "playerError", 0, -1);
                        } else if (state ==
                                VolleyResponse.NetworkResponseState.RESULT_ERROR) {
                            mLoadListener.requestError(mPlayFlow.getContext()
                                    .getString(R.string.commit_error_info), PlayConstant.PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED);
                            //                        mTrailListener.hide();
                            mObservable.notifyObservers(new AlbumPlayFlowObservable.PlayErrorCodeNotify(PlayConstant.PlayErrCode.ADDRESS_OR_DATA_ACQUIRED_FAILED, true));
//                            mPlayCallBackState = 6;
                        }

                        if (state !=
                                VolleyResponse.NetworkResponseState.SUCCESS) {
                            mPlayFlow.addPlayInfo("从网络获取播放地址失败",
                                    state + "");
                        }
                    }

                })
                .add();
    }


    /**
     * 设置是否开启P2P
     */
    private void setP2pMode() {
        switch (NetworkUtils.getNetworkType(mPlayFlow.getContext())) {
            case NetworkConstant.NETWORK_TYPE_2G:
            case NetworkConstant.NETWORK_TYPE_3G:
               mPlayFlow.setIsP2pMode(false);
                break;
            default:
                mPlayFlow.setIsP2pMode(PreferencesManager.getInstance(mPlayFlow.getContext()).getUtp());
                break;
        }

//        if (mIsDolby) {
//            mIsP2pMode = false;
//        }
    }

    /**
     * 请求真实播放地址前的验证
     *
     * @return
     */
    protected boolean onPreRequestRealPlayUrl() {
        if (mPlayFlow.getmVideoFile() == null) {
            return false;
        }

        int playLevel = PreferencesManager.getInstance(mPlayFlow.getContext()).getPlayLevel();
        int currentState = NetworkUtils.getNetworkType(mPlayFlow.getContext());


        LogInfo.log("sguotao", "curr playLevel:" + playLevel);
        DDUrlsResultBean ddUrlsResultBean =
                PlayUtils.getDDUrls(mPlayFlow.getmVideoFile(), playLevel, mPlayFlow.isDolby(), LetvSDK.getInstance()
                        .getSuppportTssLevel());
        if (ddUrlsResultBean != null && !BaseTypeUtils.isArrayEmpty(ddUrlsResultBean.getDdurls())) {
//            mDdUrlsResult = ddUrlsResultBean;
            mPlayFlow.setDdUrlsResult(ddUrlsResultBean);
            int  mPlayLevel = ddUrlsResultBean.getPlayLevel();
            String  streamType = ddUrlsResultBean.streamType;
            LogUtil.e("streamType====" + streamType);
            if (!mPlayFlow.isDolby()) {
                // 如果不是杜比频道进入取地址判断是否需要变更为杜比
//                mIsDolby = mDdUrlsResult.isDolby();
             mPlayFlow.setDobly(ddUrlsResultBean.isDolby());
            }

            mPlayFlow.getStreamSupporter().init(ddUrlsResultBean);
            LogInfo.log("sguotao",
                    "----LetvMediaPlayerManager.getInstance().isSupportHardDecode()" +
                            LetvMediaPlayerManager.getInstance().getHardDecodeSupportLevel());

            // 添加判断是否支持硬解播放器
//            if (mHardDecode && mFlowStyle == FlowType.Album) {
//                // 获取硬解播放器支持的最大码流
//                mStreamSupporter.initHW(mDdUrlsResult);
//            }

//            mStreamLevel = ddUrlsResultBean.getStreamLevel();
            mPlayFlow.setStreamLevel(ddUrlsResultBean.getStreamLevel());

            mPlayFlow.getObserver().notifyObservers(AlbumPlayFlowObservable.ON_STREAM_INIT);
            mPlayFlow.getPlayInfo().mIsGslb = true;
            /* 次元暂无广告
            if (mPlayFlow.getPlayingVideo().needPay()) {
                // 付费视频试看
                AdsManager.getInstance()
                        .getFrontVipAd(mContext, mCurrentPlayingVideo.getCid(), mAid, mVid, mCurrentPlayingVideo
                                        .getMid(), mPlayInfo.mUuidTimp, PreferencesManager.getInstance()
                                        .getUserId(),
                                mCurrentPlayingVideo.getDuration() +
                                        "", "", "0", mCurrentPlayingVideo.needPay(), true, "2");// 上报广告动作
            }
            */
            return true;
        } else {
            //视频暂无法播放
            mPlayFlow.getLoadListener().requestError(mPlayFlow.getContext().getString(R.string.commit_error_info), PlayConstant.PlayErrCode.DOWNLOAD_VIDEO_FILE_FAILED);
//            mCanToPip = false;
            mPlayFlow.getObserver().notifyObservers(new AlbumPlayFlowObservable.PlayErrorCodeNotify(PlayConstant.PlayErrCode.DOWNLOAD_VIDEO_FILE_FAILED, true));
            mPlayFlow.getPlayInfo().mIsGslb = false;
        }

        return false;
    }

    /**
     * 获取真实播放地址之后的操作
     */
    protected void onAfterFetchRealUrl(RealPlayUrlInfoBean result, boolean fromCde) {
        LogUtil.e("onAfterFetchRealUrl");
//        if (mIsWo3GUser) {
//            // 已订购,获取免流量地址
//            //            onFetchRealUrlWithWo3GUser(result, false);
//        } else {
            if (fromCde && mPlayFlow.isP2pMode()) {// && !NetworkUtils.checkIsProxyNet(mContext)
                AlbumUrl mAlbumUrl = mPlayFlow.getAlbumUrl();
                if (mAlbumUrl.p2pPlayer == null) {
                    mAlbumUrl.p2pPlayer = new PlayUrl(LetvSDKUtils.getCdeHelper(mPlayFlow.getContext())
                            .getServicePort(), mAlbumUrl.p2pUrl, "",
                            "playpos=" + mPlayFlow.getPlayRecordStep());
                    mAlbumUrl.realUrl = mAlbumUrl.p2pPlayer.getPlay();
                }
                mPlayFlow.addPlayInfo("P2P获取真实地址 realUrl", mAlbumUrl.realUrl);
                // dlna.playUrl = realUrl;
                LetvLogApiTool.createPlayLogInfo("getRealPlayUrlForP2p",
                        mPlayFlow.getVid() + "", "realUrl=" + mAlbumUrl.realUrl + " playLevel=" + mPlayFlow.getPlayLevel());
            } else {
                if (result != null && result.getCode() == 200) {
                    mPlayFlow.getAlbumUrl().realUrl = result.getRealUrl();
                    mPlayFlow.addPlayInfo("不走p2p,请求获取真实地址 realUrl", mPlayFlow.getAlbumUrl().realUrl);
                    // dlna.playUrl = realUrl;
                    LetvLogApiTool.createPlayLogInfo("getRealPlayUrlForNormalPlay",
                            mPlayFlow.getVid() + "", "realUrl=" + mPlayFlow.getAlbumUrl().realUrl + " playLevel=" + mPlayFlow.getPlayLevel());
                } else {
                    mPlayFlow.getLoadListener().jumpError(-1);
                    //                    mTrailListener.hide();
                    mPlayFlow.getObserver().notifyObservers(new AlbumPlayFlowObservable.PlayErrorCodeNotify(PlayConstant.PlayErrCode.SECURITY_CHAIN_URL_SCHEDULING, true));
//                    mPlayCallBackState = 6;
                    return;
                }
            }

//            if (!mIsPlayFreeUrl) {
                // 非联通
                // zhuqiao dlna
                boolean isShow3gDialog = shouldShowNetChangeDialog();
             if (!isShow3gDialog)
             {
               fireEvent(PlayFlowEvents.Play_StartPlay);
             }
//                if (mPlayCallBackState != 7) {
//                    if (!isShow3gDialog) {
////                        if (!getFrontAdNormal(false)) {
////                            startPlayNet();
//                        fireEvent(PlayFlowEvents.Play_StartPlay);
////                        }
//                    }
//                } else {
//                    if (!isShow3gDialog) {
////                        startPlayNet();
//                        fireEvent(PlayFlowEvents.Play_StartPlay);
//
//                    }
//                }
////            } else {
////                // 联通
////                startPlayNet();
////            }
////        }
    }

    /**
     * 是否需要显示 3G/2G/4G网络变化 弹出框
     */
    private boolean shouldShowNetChangeDialog() {
//        if (mIsWo3GUser) {
//            return false;
//        }

        if (!PreferencesManager.getInstance(mPlayFlow.getContext()).isShow3gDialog()) {
            return false;
        }

        LogInfo.log("zhuqiao", ".....showNetChangeDialog.....");
        boolean isDownLoad = mPlayFlow.getPlayingVideo() == null ? false
                : LetvUtils.isInFinish(mPlayFlow.getPlayingVideo()
                .getId());
        if (!isDownLoad /*&& !mIsDownloadFile*/ &&
                ((NetworkUtils.getNetworkType(mPlayFlow.getContext()) == NetworkConstant.NETWORK_TYPE_2G ||
                        NetworkUtils.getNetworkType(mPlayFlow.getContext()) ==
                                NetworkConstant.NETWORK_TYPE_3G))) {// 非wifi播放非本地视频
            mPlayFlow.getLoadListener().finish();
//            if (mHasAd) {
//                mAdListener.setADPause(true);
//            }
            mPlayFlow.getObserver().notifyObservers(AlbumPlayFlowObservable.ON_SHOW_3G);
            // 5.7 网络环境切换弹出框曝光
            mPlayFlow.getVideoListener().setEnforcementPause(true);
            mPlayFlow.getVideoListener().pause();
            // 统计
            StatisticsUtils.staticticsInfoPost(mPlayFlow.getContext(), "19", "c68", "0015", 4, null,
                    UIsUtils.isLandscape(mPlayFlow.getContext()) ? PageIdConstant.fullPlayPage
                            : PageIdConstant.halpPlayPage, null, null, null, null, null);
            return true;
        }
        return false;
    }
}
